//
//  GoodInfoController.m
//  ai2ban
//
//  Created by Heartbeats on 2018/1/11.
//  Copyright © 2018年 mac book pro. All rights reserved.
//

#import "GoodInfoController.h"
#import <SDCycleScrollView.h>
#import "GoodInfoTableHeaderView.h"
#import "CustomizaOrderConfirmControl.h"
#import "FictitiousOrderConfirmControl.h"


@implementation ProductParam
-(instancetype) initWithId: (NSString *)id andCount:(int)count {
    if(self = [super init]) {
        _count = count;
        _id = id;
    }
    return self;
}

@end


@implementation GoogInfoDetailCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.detailLab.textColor = [UIColor lightGrayColor];
    self.detailLab.font = [UIFont systemFontOfSize:15];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

@end

@implementation GoodInfoCell

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

@end


@interface GoodInfoController ()<UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;
@property (weak, nonatomic) UIView *bannerImgView;
@property(nonatomic, strong) NSMutableDictionary *imageHigDict;
@property(nonatomic, strong) NSMutableArray *imageArray;
@property(nonatomic, strong) GoodInfoTableHeaderView *headerView;


@end

@implementation GoodInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"商品兑换详情";
    self.view.backgroundColor = kWhiteColor;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.mj_w, self.view.mj_h - 50)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"GoodInfoCell" bundle:nil] forCellReuseIdentifier:@"GoodInfoCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GoogInfoDetailCell" bundle:nil] forCellReuseIdentifier:@"GoogInfoDetailCell"];
    [self.view addSubview:self.tableView];
    self.headerView = LOADNIB(@"GoodInfoTableHeaderView");
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.estimatedRowHeight = 44;
    
    UIView *footerView = [[NSBundle mainBundle] loadNibNamed:@"GoodInfoTableHeaderView" owner:nil options:nil][2];
    footerView.frame = CGRectMake(0, self.view.mj_h - 50, self.view.mj_w, 50);
    [self.view addSubview:footerView];
    
    self.imageHigDict = [[NSMutableDictionary alloc] init];
    self.imageArray = [[NSMutableArray alloc]  init];
    [self imageCount];
    [self updateGoodData];
}

- (IBAction)exchangeAction:(UIButton *)sender {
    if (![AppManager userIsLogin]) {
        [self presentViewController:[AppManager loginViewControl] animated:true completion:nil];
        return;
    }
    sender.enabled = NO;
    NSMutableArray *productArr = [[NSMutableArray alloc] init];
    NSDictionary *proDict = @{@"count": @(1), @"id": self.goodModel.productId};
    [productArr addObject:proDict];
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:productArr options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSDictionary<NSString *, NSString *> *param = @{@"type" : @"1", @"userId": AppManager.userId, @"productIds" : jsonResult, @"addressid": @"", @"recevephone": AppManager.user.telephone, @"recevename": AppManager.user.userName, @"startTime": @"", @"sellUserId": self.goodModel.userId, @"endTime": @"", @"buyerMessage": @""};
    NSArray *keyArray = [param allKeys];
    NSString *paramStr = @"";
    for (NSString *key in  [keyArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]) {
        paramStr = [NSString stringWithFormat:@"%@%@=%@&",paramStr, key, [param objectForKey:key]];
    }
    paramStr = [NSString stringWithFormat:@"%@%@=%@&", paramStr, @"srcKey", @"NFRs4PxuGQFIot3T"];
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionaryWithDictionary:param];
    [paramDict setObject:[NSString md5:paramStr] forKey:@"MD5"];
    [[NetworkManager shareNetwork] requestWithURLString:@"app/system/payProduct" parameters:paramDict method:@"POST" callBack:^(id responseObject) {
        sender.enabled = true;
        if ([responseObject[@"state"] intValue]) {
            FictitiousOrderConfirmControl *controller = [[FictitiousOrderConfirmControl alloc] initWithNibName:@"FictitiousOrderConfirmControl" bundle:nil];
            controller.goodModel = self.goodModel;
            controller.orderInfoModel = responseObject[@"data"];
            [self.navigationController pushViewController:controller animated:true];
            return;
        }
        [MozTopAlertView showWithType:1 text:[NSString stringWithFormat:@"%@", responseObject[@"data"]] parentView:nil];
    }];
}

-(void) updateGoodData {
    self.headerView.goodModel = self.goodModel;
    [self.tableView reloadData];
}

- (void)setGoodModel:(JiFenGoodModel *)goodModel {
    _goodModel = goodModel;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.imageArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        GoogInfoDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoogInfoDetailCell" forIndexPath:indexPath];
        cell.detailLab.text = self.goodModel.introduce;
        return cell;
    }
    GoodInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodInfoCell" forIndexPath:indexPath];
    [cell.goodImgV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", ImageBaseUrl, self.imageArray[indexPath.row - 1]]] placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (image.size.height) {
            if ([self.imageHigDict objectForKey:TO_STR((indexPath.row - 1))]) {
                return;
            }
            CGFloat imageW = [UIScreen mainScreen].bounds.size.width;
            CGFloat ratio = image.size.height / image.size.width;
            CGFloat imageH = ratio * imageW + 8;
            [self.imageHigDict setObject:@(imageH) forKey:TO_STR(indexPath.row - 1)];
            [self.tableView beginUpdates];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
        }
    }];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[NSBundle mainBundle] loadNibNamed:@"GoodInfoTableHeaderView" owner:nil options:nil][1];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return UITableViewAutomaticDimension;
    }
    return [[self.imageHigDict objectForKey:TO_STR(indexPath.row - 1)] floatValue];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 52;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void) imageCount {
    if ([self.goodModel.picImg1 length] > 0) {
        [self.imageArray addObject:self.goodModel.picImg1];
    }
    if ([self.goodModel.picImg2 length] > 0) {
        [self.imageArray addObject:self.goodModel.picImg2];
    }
    if ([self.goodModel.picImg3 length] > 0) {
        [self.imageArray addObject:self.goodModel.picImg3];
    }
    if ([self.goodModel.picImg4 length] > 0) {
        [self.imageArray addObject:self.goodModel.picImg4];
    }
    if ([self.goodModel.picImg5 length] > 0) {
        [self.imageArray addObject:self.goodModel.picImg5];
    }
    if ([self.goodModel.picImg length] > 0) {
        [self.imageArray addObject:self.goodModel.picImg];
    }
}

@end
